package com.tjetc.controller;

import com.tjetc.domain.User;
import com.tjetc.service.UserService;
import com.tjetc.utils.JwtUtils;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController

@CrossOrigin
@RequestMapping("/user")
public class UserController {
    @Resource
    private UserService userService;
    @Resource
    private RedisTemplate redisTemplate;
    @RequestMapping("/findUserByUserId")
    public List<User> findUserByUserId(@RequestParam("userId")Integer userId ,
                                       @RequestParam("receiverId")Integer receiverId){
        System.out.println("开始查用户信息");
        System.out.println("UserController.findUserByUserId");
        return userService.findUserByUserId(userId,receiverId);
    }
    @PostMapping("/loginByPwd")
    public Map<String, Object> loginByPwd(@RequestParam String phone, @RequestParam String password) {

        Map<String, Object> result = new HashMap<>();
        // 从ES查找用户
        User user = userService.getUserByPhone(phone);
        if (user == null) {
            result.put("success", false);
            result.put("message", "用户不存在");
            return result;
        }
        // 校验密码（明文，实际建议加密）
        if (!password.equals(user.getPassword())) {
            result.put("success", false);
            result.put("message", "密码错误");
            return result;
        }
        // 生成token
        Map<String, Object> claims = new HashMap<>();
        claims.put("id", user.getId());
        claims.put("phone", user.getPhone());
        String token = JwtUtils.createJwtToken(claims);
        result.put("success", true);
        result.put("token", token);
        result.put("user", user);
        // 新增：同一用户只允许一个token有效
        String oldToken = (String) redisTemplate.opsForValue().get("login:user:" + user.getId());
        if (oldToken != null) {
            redisTemplate.delete("login:token:" + oldToken);
        }
        // token存入Redis
        redisTemplate.opsForValue().set("login:token:" + token, String.valueOf(user.getId()), 7, java.util.concurrent.TimeUnit.DAYS);
        redisTemplate.opsForValue().set("login:user:" + user.getId(), token, 7, java.util.concurrent.TimeUnit.DAYS);
        return result;
    }
    @RequestMapping("findOther")
    public List<String> findOther(@RequestParam("userId")Integer userId){
       return userService.findOther(userId);
    }


}
